﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tuzzit_Modele;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Shell;
using System.Resources;

namespace Tuzzit
{
    public partial class ProfilPivot : PhoneApplicationPage
    {
        public ProfilPivot()
        {
            InitializeComponent();
            ShowRandom();
            GetProjects();
            GetName();
            HeaderProjet.Header = AppResources.ProfilPivotProjetTitle;
            HeaderMap.Header = AppResources.ProfilPivotMapTitle;
        }

        private void GetProjects()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/user_controller.php?function=get_projects_for_user&format=json");
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
        }

        private void ReadWebRequestCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;

            /*foreach (Cookie ck in myResponse.Cookies)
            {
                            

                Dispatcher.BeginInvoke(() => MessageBox.Show("#"+ck.Name +"# = "+ck.Value));
            }*/

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
               // Dispatcher.BeginInvoke(() => MessageBox.Show(results.ToString()));//-- on another thread!

                Dispatcher.BeginInvoke(() => ResponseProcessing(results));
            }
            myResponse.Close();
        }

        private void ResponseProcessing(string response)
        {
            //response = Regex.Replace(response, "\"", "\"\"");

            //string lresponse = @"{""responseData"": [{""project_id"":117,""0"":117,""favorite"":false,""1"":false,""name"":""MASI Interns"",""2"":""MASI Interns"",""description"":""We are going to improve and code TUZZit to make it so magic"",""3"":""We are going to improve and code TUZZit to make it so magic"",""visibility"":2,""4"":2,""lat"":""50.2123358"",""5"":""50.2123358"",""long"":""5.3303156"",""6"":""5.3303156"",""project_hashcode"":""51724142776147594a6b32766b42384b3746306535513d3d"",""project_path"":""http:\/\/dev.tuzzit.com\/project\/51724142776147594a6b32766b42384b3746306535513d3d"",""has_warning"":true,""project_img"":""public\/media\/project\/project_img_117.png"",""mail_count"":1},{""project_id"":4242,""0"":117,""favorite"":false,""1"":false,""name"":""MASI Interns"",""2"":""MASI Interns"",""description"":""We are going to improve and code TUZZit to make it so magic"",""3"":""We are going to improve and code TUZZit to make it so magic"",""visibility"":2,""4"":2,""lat"":""50.2123358"",""5"":""50.2123358"",""long"":""5.3303156"",""6"":""5.3303156"",""project_hashcode"":""51724142776147594a6b32766b42384b3746306535513d3d"",""project_path"":""http:\/\/dev.tuzzit.com\/project\/51724142776147594a6b32766b42384b3746306535513d3d"",""has_warning"":true,""project_img"":""public\/media\/project\/project_img_117.png"",""mail_count"":1}]}";
            response = @"{""responseData"": " + response + "}";

            JObject o = JObject.Parse(response);
            List<ModeleProfil> listProject = new List<ModeleProfil>();

            Map MapProject = new Map();
            MapProject.CopyrightVisibility = Visibility.Collapsed;
            MapProject.LogoVisibility = Visibility.Collapsed;
            MapProject.ScaleVisibility = Visibility.Collapsed;
            MapProject.ZoomLevel = 8;
            MapProject.CredentialsProvider = new ApplicationIdCredentialsProvider("AgXCIYxajlJXsSGnBvEFcS0QBUyWyxppoTy7xrIqun-D3_A0p2F8qiDJOo8xEr-3");
            MapProject.Center = new GeoCoordinate(50.226007, 5.329742);

            Pushpin pin;
           
            foreach (JObject tmp in o["responseData"])
            {
                ModeleProfil vartmp = new ModeleProfil(
                        (string)tmp.SelectToken("project_id"),
                        (bool)tmp.SelectToken("favorite"),
                        (string)tmp.SelectToken("name"),
                        (string)tmp.SelectToken("description"),
                        (int)tmp.SelectToken("visibility"),
                        (string)tmp.SelectToken("lat"),
                        (string)tmp.SelectToken("long"),
                        (string)tmp.SelectToken("project_hashcode"),
                        (string)tmp.SelectToken("project_path"),
                        (bool)tmp.SelectToken("has_warning"),
                        (string)tmp.SelectToken("project_img"),
                        (int)tmp.SelectToken("mail_count")
                );
                listProject.Add(vartmp);

                GeoCoordinate d = new GeoCoordinate((double)tmp.SelectToken("lat"), (double)tmp.SelectToken("long"));
                pin = new Pushpin();
                pin.Location = d;
                pin.Content = (string)tmp.SelectToken("name");
                pin.Name = (string)tmp.SelectToken("project_hashcode");
                pin.MouseLeftButtonUp += new MouseButtonEventHandler(pin_Click);
                
                //pin.MouseLeftButtonUp += new MouseButtonEventHandler(MouseLeftButtonUp);
                MapProject.Children.Add(pin);
            }
            ProjectsList.ItemsSource = listProject;
           
            //MapProject.Center = new GeoCoordinate(47.6097, -122.3331);
            ContentPanelMap.Children.Add(MapProject);
            //MessageBox.Show(vartmp);
            //string something = (string)o["responseData"][0]["project_id"] +" "+ (string)o["responseData"][1]["project_id"];
            //MessageBox.Show(something);

        }

        private void UserLogout(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/logout.php?hashcode=55532d2a2d3131352d2a2d");
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        private void ReadCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => logout_success(results.Trim()));
            }
            myResponse.Close();
        }

        private void logout_success(string res)
        {
            //MessageBox.Show("#"+res.ToString()+"#");
            if (res != "")
            {
                MessageBox.Show("An error occured !");
            }
            else
            {
                ResourceManager resourceManager = new ResourceManager("Tuzzit.AppResources", GetType().Assembly);
                MessageBox.Show((String)resourceManager.GetObject("ProjetPivotMessageBoxLoggedOut"));
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void GetName()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/");
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
            request.BeginGetResponse(new AsyncCallback(ReadWebNameCallback), request);
        }

        private void ReadWebNameCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
               // Dispatcher.BeginInvoke(() =>MessageBox.Show(results.ToString())); //-- on another thread!
                Dispatcher.BeginInvoke(() => NameProcessing(results));
            }
            myResponse.Close();
        }

        private void NameProcessing(string response)
        {
            response = "@" + response.Substring(50,85);
            response = Regex.Replace(response, @"\n", "");
            response = Regex.Replace(response, @"\t", "");
            response = Regex.Replace(response, @".*<title>", "");
            response = Regex.Replace(response, @"</title>.*", "");
            //MessageBox.Show(response.ToString());
            PivotTitle.Title = response.ToString();
        }

        private void GoToProject( object sender, System.Windows.Input.GestureEventArgs e)
        {
           ModeleProfil item = (ModeleProfil)this.ProjectsList.SelectedItem;
           NavigationService.Navigate(new Uri("/ProjetsPivot.xaml?hash=" + item.Project_hashcode + "&pname=" + item.Name, UriKind.RelativeOrAbsolute));
        }

        private void pin_Click(object sender, MouseButtonEventArgs e)
        {
            Pushpin pin = (Pushpin)sender;
            NavigationService.Navigate(new Uri("/ProjetsPivot.xaml?hash=" + pin.Name + "&pname=" + pin.Content, UriKind.RelativeOrAbsolute));            
        }
        private void AddProject(object sender, EventArgs e)
        {
            ResourceManager resourceManager = new ResourceManager("Tuzzit.AppResources", GetType().Assembly);
            MessageBox.Show((String)resourceManager.GetObject("ProjetPivotMessageBoxNotImplemented"));
        }
        private void About(object sender, EventArgs e)
        {
           NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Refresh(object sender, EventArgs e)
        {
            GetProjects();
        }

        private void Settings(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/UserSettings.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ShowRandom()
        {
            //ne pas oulier de virer le bouton du XAML :)
            if ((Application.Current as App).Motd.MyItems.Count > 0)
            {
                Random random = new Random();
                int randomNumber = random.Next(0, (Application.Current as App).Motd.MyItems.Count);
                ModeleMessage itemSelected = (Application.Current as App).Motd.MyItems.ElementAt(randomNumber);
                MessageBox.Show(itemSelected.MessageToAdd);
            }
        }
    }
}